package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.CommentMessageAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CommentInfoEntity;
import com.runen.infinitemovement.model.entity.PriseEntity;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.model.entity.SecondCommentReplyEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.widget.CustomLoadMoreView;
import com.runen.infinitemovement.widget.goodview.GoodView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on 2020/09/25 14:56
 */
public class SecondReplyCommentActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.rci_user_header)
    RoundedCornersImage rciUserHeader;
    @BindView(R.id.tv_userName)
    TextView tvUserName;
    @BindView(R.id.tv_user_praise_sum)
    TextView tvUserPraiseSum;
    @BindView(R.id.iv_user_praise)
    ImageView ivUserPraise;
    @BindView(R.id.ll_praise_sum)
    LinearLayout llPraiseSum;
    @BindView(R.id.tv_comment_time)
    TextView tvCommentTime;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.tv_myself_comment)
    TextView tvMyselfComment;
    @BindView(R.id.rv_comment_info)
    RecyclerView rvCommentInfo;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.edt_input_message)
    EditText edtInputMessage;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    private CommentMessageAdapter commentMessageAdapter;
    private ReplyCommentListBean replyCommentListBean;
    private CommentInfoEntity.DataBean commentInfoEntity;
    private CommentInfoEntity.DataBean commentInfoEntity2;
    private long articleId;
    private long topCommentId;
    private String commentId;
    private String targetId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_second_reply_comment;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("评论详情");
        srl.setOnRefreshListener(this);
        commentId = getIntent().getStringExtra("commentId");
        targetId = getIntent().getStringExtra("targetId");
//        commentDetailListBean = JsonUtils.fromJson(getIntent().getStringExtra("itemCommentInfo"), CommentDetailListBean.class);
//        commentDetailListBean2 = commentDetailListBean;
//        articleId = getIntent().getLongExtra("articleId", 1L);
//        topCommentId = getIntent().getLongExtra("topCommentId", 0L);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        rvCommentInfo.setLayoutManager(layoutManager);
        commentMessageAdapter = new CommentMessageAdapter(this);
        commentMessageAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        rvCommentInfo.setAdapter(commentMessageAdapter);


        edtInputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentInfoEntity2, replyCommentListBean);
                    }
                }
                return false;
            }
        });

        commentMessageAdapter.setOnSecondItemClick(new CommentMessageAdapter.OnSecondItemClick() {
            @Override
            public void onItemClick(ReplyCommentListBean secondItem) {
                replyCommentListBean = secondItem;
                edtInputMessage.setHint("回复" + replyCommentListBean.reviewerName + "：");
                commentInfoEntity2 = null;
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onMoreClick() {

            }
        });

        initPageView();
        initLoadMore();
    }

    private void initLoadMore() {
        commentMessageAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreRequested();
            }
        });
        commentMessageAdapter.getLoadMoreModule().setAutoLoadMore(true);
        commentMessageAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void initPageView() {
        String str = "?commentId=%s";
        new ActivityAPI().CommentInfo(String.format(str, commentId), new BaseResultCallback<CommentInfoEntity>() {
            @Override
            public void onResponse(CommentInfoEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        showView(response.data);
                    }
                }

            }
        });
    }

    private void showView(CommentInfoEntity.DataBean response) {
        if (response != null) {
            initData();
            commentInfoEntity = response;
            commentInfoEntity2 = commentInfoEntity;
            tvUserName.setText(response.nickname);
            GlideUtils.loadImage(this, response.headImgUrl+"?x-oss-process=image/resize,m_fill,w_144,h_144", rciUserHeader);
            tvCommentTime.setText(TimeUtil.converFromSecondTime(TimeUtil.getDateTimeToLong(TimeUtil.dealDateFormat(response.createTime))));
            tvUserPraiseSum.setText(String.valueOf(response.likeNumber));
            if (response.isLike) {
                GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_praised), ivUserPraise);
                tvUserPraiseSum.setTextColor(CommonUtil.getColor(R.color.color_FFF55656));
            } else {
                GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_like), ivUserPraise);
                tvUserPraiseSum.setTextColor(CommonUtil.getColor(R.color.color_FFBCBCBC));
            }
            tvMyselfComment.setText(response.content);
        }

    }

    private void onComment(String edtString, CommentInfoEntity.DataBean commentDetailList, ReplyCommentListBean replyCommentList) {
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "1");
            object.put("content", edtString);
            object.put("targetId", targetId);
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", commentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(SecondReplyCommentActivity.this);
                edtInputMessage.setText("");
                edtInputMessage.setHint("说点什么...");
                commentInfoEntity2 = commentInfoEntity;
                replyCommentListBean = null;
                onRefresh();
            }
        });
    }

    private void initData() {
        String str = "?commentId=%s&limit=%s&page=%s";
        srl.setRefreshing(true);
        new ActivityAPI().secondComment(String.format(str, commentId, 20, 1), new BaseResultCallback<SecondCommentReplyEntity>() {
            @Override
            public void onResponse(SecondCommentReplyEntity response) {
                srl.setRefreshing(false);
                commentMessageAdapter.setNewData(response.data);
                if (commentMessageAdapter.getData().size() >= response.count) {
                    commentMessageAdapter.getLoadMoreModule().setEnableLoadMore(false);
                    commentMessageAdapter.getLoadMoreModule().loadMoreEnd(true);
                }
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.ll_praise_sum, R.id.tv_myself_comment, R.id.rci_user_header})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.ll_praise_sum:
                if (null != commentInfoEntity) {
                    praise();
                }
                break;
            case R.id.tv_myself_comment:
                if (null != commentInfoEntity) {
                    commentInfoEntity2 = commentInfoEntity;
                    edtInputMessage.setHint("回复" + commentInfoEntity2.nickname + "：");
                    CommonUtil.showKeyboard(edtInputMessage);
                }
                break;
            case R.id.rci_user_header:
                Intent intent = new Intent(this, MyHomeActivityV2.class);
                intent.putExtra("userId", commentInfoEntity.reviewerId);
                startActivity(intent);

                break;
        }
    }

    private void praise() {
        if (commentInfoEntity2 == null) {
            commentInfoEntity2 = commentInfoEntity;
        }
        if (commentInfoEntity2.isLike) {
            commentInfoEntity2.isLike = false;
            commentInfoEntity2.likeNumber = commentInfoEntity2.likeNumber - 1;
            GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_like), ivUserPraise);
            tvUserPraiseSum.setTextColor(CommonUtil.getColor(R.color.color_FFBCBCBC));
        } else {
            commentInfoEntity2.isLike = true;
            commentInfoEntity2.likeNumber = commentInfoEntity2.likeNumber + 1;
            GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_praised), ivUserPraise);
            GoodView goodView = new GoodView(this);
            goodView.setImage(R.mipmap.ico_praised);
            goodView.show(ivUserPraise);
            tvUserPraiseSum.setTextColor(CommonUtil.getColor(R.color.color_FFF55656));
        }
        tvUserPraiseSum.setText(String.valueOf(commentInfoEntity2.likeNumber));
        //点赞或取消点赞
        sendOrCancelPrise(commentInfoEntity, 2);
    }

    private void sendOrCancelPrise(CommentInfoEntity.DataBean commentDetailListBean, int type) {
        JSONObject object = new JSONObject();
        try {
            object.put("toLikeUserId", commentDetailListBean.reviewerId);
            object.put("likeDataId", commentDetailListBean.commentId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().commentLikeAndCancel(commentDetailListBean.isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
               if (response.getCode()!=0){
                   ToastUtils.showShort(response.getMessage());
               }
            }

            @Override
            public void onComplete() {
                super.onComplete();
//                if (commentDetailListBean.isLike) {
//                    ToastUtils.showShort("点赞成功");
//                } else {
//                    ToastUtils.showShort("取消点赞成功");
//                }
            }
        });
    }

    private int page = 2;

    public void loadMoreRequested() {
        String str = "?commentId=%s&limit=%s&page=%s";
        new ActivityAPI().secondComment(String.format(str, commentId, 20, page), new BaseResultCallback<SecondCommentReplyEntity>() {
            @Override
            public void onResponse(SecondCommentReplyEntity response) {
                if (response.data != null) {
                    commentMessageAdapter.addData(response.data);
                    if (commentMessageAdapter.getData().size() >= response.count) {
                        commentMessageAdapter.getLoadMoreModule().loadMoreEnd(true);
                        commentMessageAdapter.getLoadMoreModule().setEnableLoadMore(false);
                    } else {
                        page++;
                        commentMessageAdapter.getLoadMoreModule().loadMoreComplete();
                        commentMessageAdapter.getLoadMoreModule().setEnableLoadMore(true);
                    }
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 2;
        initData();
    }
}
